import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/app_plugin.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/model/config_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../http/bean/config/server_code_bean.dart';

///服务器地址配置
class SerVerAddressRoute extends StatefulWidget {
  @override
  _SerVerAddressState createState() => _SerVerAddressState();
}

class _SerVerAddressState extends State<SerVerAddressRoute> {
  _SerVerAddressPresenter? presenter = null;

  @override
  void initState() {
    super.initState();
    if (presenter == null) {
      presenter = _SerVerAddressPresenter(context, setState, this);
    }
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    marginTop = px.y(180);
    var scaffold = Scaffold(
      backgroundColor: AppColors.backgroundColorWithWhite,
      appBar: AppBar(
        backgroundColor: AppColors.backgroundColorWithWhite,
        elevation: 0,
        leading: AppUi.getBack(context, () {
          var isBack = presenter?.back(context);
          if (isBack != null && isBack) {
            return false;
          }
          return true;
        }),
      ),
      body: Material(
          color: AppColors.backgroundColorWithWhite, child: _body(context)),
    );
    return WillPopScope(
      child: scaffold,
      onWillPop: () async {
        var isBack = presenter?.back(context);
        return isBack ?? true;
      },
    );
  }

  var marginTop = 0.0;

  Widget _body(BuildContext context) {
    return Scrollbar(
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
            key: _formKey,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: px.y(200)),
                  child: Align(
                    child: Hero(
                      tag: AppUi.hero_tag_launch,
                      child: Image.asset(
                        ImagePathUtils.getPathWithImage("ic_logo_blue.png"),
                        width: px.dp(331),
                        height: px.dp(203),
                      ),
                    ),
                    alignment: Alignment.topCenter,
                  ),
                ),
                //历史域名
                _addressHistory(),
                //服务器地址
                Center(
                  child: Container(
                    margin:
                        AppEdgeInsets.marginWithItem(top: marginTopServer()),
                    child: _serverAddress(),
                  ),
                ),
                //邀请码
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _inviteCode(),
                  ),
                ),
                //保存按钮
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: MaterialButton(
                      height: 55,
                      minWidth: px.screenWidth(),
                      onPressed: () {
                        //print('点击事件${presenter.toString()}');
                        var b = _formKey.currentState?.validate() ?? false;
                        if (b) {
                          //fixme 必须添加点击事件，不然背景色color不起作用。
                          presenter?.getAppCode(context, true);
                        }
                      },
                      //label 右边控件（一般为文本），不能为空
                      color: AppColors.themeColorWithServerAdress,
                      //color 按钮颜色
                      splashColor: Colors.black12,
                      //splashColor 点击时，飞溅扩散的颜色
                      //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
                      colorBrightness: Brightness.light,
                      //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(60))),
                      //shape 形状
                      textColor: Colors.white,
                      //文本默认颜色
                      child: Text(
                        AppStrings.of(context).save,
                        style: AppStyle.textStyleWithButton(),
                      ), //fixme 子控件
                    ),
                  ),
                )
              ],
            )),
      ),
    );
  }

  //历史域名
  Widget _addressHistory() {
    return AppUi.getSeverAdressHistoryLayout(context, (value) {
      //服务器域名点击回调
      _serverTextEditingController?.text = value;
      presenter?.serverContent = value;
    });
  }

  double marginTopServer() {
    List<String>? adressHistory = AppDataConfig.getAdressHistory();
    if (StringUtils.isEmpty(adressHistory)) {
      return marginTop;
    } else {
      return px.y(50);
    }
  }

  GlobalKey<FormState> _formKey = GlobalKey();

  //服务器地址
  TextEditingController? _serverTextEditingController;

  Widget _serverAddress() {
    if (_serverTextEditingController == null) {
      _serverTextEditingController =
          TextEditingController(text: presenter?.serverContent);
    }
    if (!StringUtils.isEmpty(presenter?.serverContent) &&
        _serverTextEditingController?.text != presenter!.serverContent) {
      _serverTextEditingController?.text = presenter!.serverContent;
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _serverTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.serverContent = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).serverAddress, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_net.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon: (isDataMoreLength(presenter?.serverContent))
                ? Container(
                    width: 40,
                    height: 40,
                    child: InkWell(
                      child: Center(
                        child: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 16,
                        ),
                      ),
                      onTap: () {
                        //文本清除
                        setState(() {
                          presenter?.serverContent = "";
                          _serverTextEditingController?.text = "";
                        });
                      },
                    ),
                  )
                : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).serverAddressNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
        );
      },
    );
  }

  //邀请码
  TextEditingController? _inviteCodeTextEditingController;

  Widget _inviteCode() {
    if (_inviteCodeTextEditingController == null) {
      _inviteCodeTextEditingController =
          TextEditingController(text: presenter?.inviteCodeContent);
    }
    if (!StringUtils.isEmpty(presenter?.inviteCodeContent) &&
        _inviteCodeTextEditingController?.text !=
            presenter!.inviteCodeContent) {
      _inviteCodeTextEditingController?.text = presenter!.inviteCodeContent;
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _inviteCodeTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.inviteCodeContent = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).inviteCode, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_password.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon: (isDataMoreLength(presenter?.inviteCodeContent))
                ? Container(
                    width: 40,
                    height: 40,
                    child: InkWell(
                      child: Center(
                        child: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 16,
                        ),
                      ),
                      onTap: () {
                        //文本清除
                        setState(() {
                          presenter?.inviteCodeContent = "";
                          _inviteCodeTextEditingController?.text = "";
                        });
                      },
                    ),
                  )
                : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).inviteCodeNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
          obscureText: true,
        );
      },
    );
  }
}

class _SerVerAddressPresenter {
  //服务器地址
  var serverContent = "";

  //邀请码
  var inviteCodeContent = "";

  StateSetter? _setState = null;

  _SerVerAddressPresenter(BuildContext context, StateSetter? setState,
      _SerVerAddressState _serVerAddressState) {
    _setState = setState;
    serverContent = AppDataConfig.getAdress() ?? "";
    inviteCodeContent = AppDataConfig.getCustomSecret() ?? "";
    if (StringUtils.isEmpty(inviteCodeContent)) {
      inviteCodeContent = "234-ZH"; //fixme 防止用户懒的输入，默认一个默认值。
    }
    // //print("进来了：$setState");
    // if (StringUtils.isEmpty(serverContent)) {
    //   AppPlugin.getBaseUrl?.then((value) {
    //     serverContent = value;
    //     //print("=====================服务器地址：" + value);
    //     _setState?.call(() {});
    //   });
    // }
    // if (StringUtils.isEmpty(inviteCodeContent)) {
    //   AppPlugin.getAppSecret?.then((value) {
    //     inviteCodeContent = value;
    //     //print("=====================安装代码：" + value);
    //     _setState?.call(() {});
    //   });
    // }
    if (StringUtils.isEmpty(serverContent)) {
      TextUtils.readCopy()?.then((value) {
        if (value != null && value.contains("Api") && value.contains("Code")) {
          try {
            ServerCode? serverCode = ServerCode();
            serverCode = GsonUtils.parseJson(value, serverCode);
            if (serverCode != null && StringUtils.isNotEmpty(serverCode?.Api)) {
              serverContent = serverCode!.Api;
              inviteCodeContent = serverCode!.Code;
              _serVerAddressState?._serverTextEditingController?.text =
                  serverContent;
              _serVerAddressState?._inviteCodeTextEditingController?.text =
                  inviteCodeContent;
              // delayed(1, () {
              //   //延迟一秒。防止过快，无法跳转到登陆页面。因为页面跳转有防止快速重复跳转的判断。
              //   getAppCode(context,false); //获取密钥，如正确，就直接跳转到登陆页面。
              // });
              getAppCode(context, false);//fixme 这里自动跳转,不开启快速防重复跳转。
            }
          } catch (e) {}
        }
      }).catchError((e) {});
    }
    // ServerCode serverCode = ServerCode();
    // serverCode.Api = "http://test.bwg2017.com/";
    // serverCode.Code = "234-ZH";
    // var json=serverCode.jsonEncodeToJson();
    // print("$json");
  }

  @override
  String toString() {
    return 'SerVerAddressPresenter{serverContent: $serverContent, inviteCodeContent: $inviteCodeContent}';
  }

  ///返回,true 关闭；false 不关闭。
  bool back(
    BuildContext context,
  ) {
    var appSecret = AppDataConfig.getAppSecret();
    if (StringUtils.isEmpty(appSecret)) {
      AppDialog.showDialogWithAlert(context,
              isOk: false, content: AppStrings.of(context).toExitWithSecret)
          ?.then((value) {
        if (BoolUtils.isBool(value)) {
          AppRouteHelper.exit();
        }
      });
      return false;
    }
    return true;
  }

  String? _correct_appSecret = null; //记录之前正确的密钥
  String? _correct_customSecret = null; //记录之前用户输入的密钥
  String? _correct_address = null; //记录之前正确的地址

  ///获取之前正确的密钥
  void _getCorrect() {
    if (StringUtils.isEmpty(_correct_appSecret)) {
      _correct_appSecret = AppDataConfig.getAppSecret();
    }
    if (StringUtils.isEmpty(_correct_customSecret)) {
      _correct_customSecret = AppDataConfig.getCustomSecret();
    }
    if (StringUtils.isEmpty(_correct_address)) {
      _correct_address = AppDataConfig.getAdress();
    }
  }

  ///恢复之前正确的密钥(防止用户误操作)
  void _setCorrect() {
    if (StringUtils.isNotEmpty(_correct_appSecret)) {
      AppDataConfig.saveAppSecret(_correct_appSecret);
    }
    if (StringUtils.isNotEmpty(_correct_customSecret)) {
      AppDataConfig.saveCustomSecret(_correct_customSecret);
    }
    if (StringUtils.isNotEmpty(_correct_address)) {
      AppDataConfig.setAdress(_correct_address);
    }
  }

  ///获取密钥（通过获取密钥，判断域名地址是否正确）
  ///isEnableFastGo 跳转登陆页面，是否开启快速仿重复跳转。
  void getAppCode(BuildContext context, bool isEnableFastGo) {
    //先获取之前正确的密钥。
    _getCorrect();
    ConfigModel.getAppCode(context, serverContent, inviteCodeContent, true,
        ((bool) {
      if (bool) {
        //密钥获取成功，开始获取工厂（验证密钥是否正确）
        getFactorygetlist(context, isEnableFastGo);
      } else {
        //域名错误
        AppDialog.showDialogWithInfo(context,
            content: AppStrings.of(context).serverAddressCorrect);
      }
    }));
  }

  ///获取工厂（判断密钥是否正确）
  void getFactorygetlist(BuildContext context, bool isEnableFastGo) {
    ConfigModel.getFactorygetlist(context, true, (value) {
      if (value == null) {
        AppDialog.showDialogWithInfo(context,
            content: AppStrings.of(context).net_error_02); //服务器连接失败
        return;
      }
      if (value != null && value.isSuccessForData()) {
        if (value != null && value.Data != null && value.Data!.length > 0) {
          Factory factory = value.Data![0];
          //默认保存第一个工厂
          AppDataConfig.saveFactory(factory);
          var mAdress = AppDataConfig.getAdress();
          AppDataConfig.addAdressHistory(mAdress); //fixme 添加域名历史记录。
          if (StringUtils.isNotEmpty(_correct_address) &&
              _correct_address == mAdress) {
            //域名没有发生改变，直接返回。
            AppRouteHelper.pop(context);
          } else {
            //域名发生改变，或者第一次设置，调整到登录页。
            AppRouteHelper.goLoginRoute(context, isEnableFastGo);
          }
        }
      } else {
        //密钥错误
        AppDialog.showDialogWithInfo(context,
            content: AppStrings.of(context).inviteCodeCorrect);
        //清空错误的密钥
        AppDataConfig.saveAppSecret(null);
        AppDataConfig.saveCustomSecret(null);
        //恢复之前正确的密钥
        _setCorrect();
      }
    });
  }
}
